<template>
  <BasicModal :width="500" v-bind="$attrs" @register="registerModal" title="添加订单" @ok="handleSubmit"
              :canFullscreen="false"
              :destroyOnClose="true"
              :maskClosable="false"
              :centered="true"
  >
    <BasicForm @register="registerForm" ref="formElRef">
      <template #cfsj="{ model, field }">
        <a-date-picker
          :showTime="false"
          valueFormat="YYYY-MM-DD"
          placeholder=" "
          v-model:value="model[field]"
          @change="getAjaxAutocomplete(model, model['ddlx'])" 
        ></a-date-picker>
      </template>
      <template #selectA="{ model, field }">
        <AutoComplete
          v-model:value="model[field]"
          style="width: 310px"
          :options="options"
          :dropdown-match-select-width="650"
          :filterOption="onFilter"
          @select="onSelect(model[field], options, model)"
          @change="onChange(model[field], model)"
        >
          <a-textarea placeholder="" class="customer" style="text-transform:uppercase"/>
        </AutoComplete>
      </template>
      <template #text="{ model, field }">
        <div> {{ model.travelLine1 ? (model[field] ? model[field] : "0/0") : '' }}</div>
      </template>
    </BasicForm>
  </BasicModal>
</template>
<script lang="ts" name="PassWordModal" setup>
import { AutoComplete } from 'ant-design-vue';
import { computed, ref, unref, watchEffect } from "vue";
import { BasicModal, useModalInner } from "/@/components/Modal";
import { BasicForm, useForm, FormActionType } from "/@/components/Form/index";
import { FormSchema } from '/@/components/Table';
import { add, ajaxAutocomplete } from "./business.api";
import { useMessage } from "/@/hooks/web/useMessage";
import { HeartTwoTone } from '@ant-design/icons-vue';
import moment from 'dayjs'
import { values } from 'xe-utils';
import { padEnd } from 'lodash-es';

// 声明Emits
const emit = defineEmits(['success', 'register']);
const $message  = useMessage();
const options   = ref<any[]>([]);
//表单所有值，外部可更新
const formElRef = ref<Nullable<FormActionType>>(null);

/**
 * ? 订单表单 - 构建
 * // 111111
 * @ ssss
 * ! ddddddd
 *  ddddddd
 */
//订单表单false
const addSchema: FormSchema[] = [
  { label: '', field: 'id', component: 'Input', show: false },
  { label: "", field: "scheduleId", component: "Input", show: false },
  { label: "", field: "travelLine", component: "Input", show: false },
  {
    label: '部门',
    field: 'ddlx',
    component: 'JDictSelectTag',
    componentProps: ({ formModel }) => {
      return {
        dictCode: 'ddlxType@ddlxUser', 
        placeholder: ' ', 
        getPopupContainer: () => document.body,
        onSelect: (e) => {
          getAjaxAutocomplete(formModel, e);
        }
      }
    },
    required: true
  },
  {
    label: '业务类型',
    field: 'ywlx',
    component: 'JDictSelectTag',
    defaultValue: 'B',
    componentProps: ({ formModel }) => {
      return {
        dictCode: 'ywlxType', 
        placeholder: ' ',
        getPopupContainer: () => document.body,
        onSelect: (e) => {
          // if (e == 'C' || e == 'F') {
          //   formModel.travelLine1 = ''
          // }
          if (e != 'D') {
            formModel.travelLine1 = ''
          }
        }
      } 
    },
    required: true,
  },
  {
    label: '出团时间',
    field: 'cfsj',
    component: 'Input',
    slot: 'cfsj',
    defaultValue: moment().format('YYYY-MM-DD'),
    required: true,
    componentProps: ({ formModel }) => {
      return {
        AutoComplete: 'off',
        placeholder: ' ',
        style: {
          padding: '0 5px!important'
        }
      };
    },
  },
  {
    label: '订单名称',
    field: 'travelLine1',
    component: 'Select',
    slot: 'selectA',
    required: true,
    ifShow: ({ values }) => {
      return (values.ywlx == 'D');
    },
    componentProps: ({ formModel }) => {
      return {
        placeholder: '请输入订单名称', 
        AutoComplete: 'off',
        onInput: (e) => {
          //console.info("input", e, formModel.travelLine1)
          //formModel.travelLine = formModel.travelLine1
        },
      }
    },
  },
  {
    label: '余位',
    field: 'residue',
    component: 'Input',
    slot: 'text',
    ifShow: ({ values }) => {
      return (values.ywlx == 'D');
    },
  },
  {
    label: '订单名称',
    field: 'travelLine2',
    component: 'Input',
    componentProps: ({ formModel }) => {
      return {
        placeholder: '请输入订单名称', 
        AutoComplete: 'off',
        onInput: (e) => {
          //console.info("loanDate@@@@", formModel.cfsj, formModel.travelLine2);
          formModel.travelLine = formModel.travelLine2
        }
      }
    },
    required: true,
    ifShow: ({ values }) => {
      return (values.ywlx != 'D');
    }, 
  },
]

//表单配置
const [registerForm, {resetFields, setFieldsValue, validate, updateSchema, clearValidate}] = useForm({
  labelWidth: 120,
  baseColProps: {span: 21},
  schemas: addSchema,
  showActionButtonGroup: false,
});

//表单赋值
const [registerModal, {setModalProps, closeModal}] = useModalInner(async (data) => {
  //重置表单
  await resetFields();
  setModalProps({confirmLoading: false});
  //清空产品名称列表
  options.value = [];
  //表单赋值
  await setFieldsValue({...data});
  clearValidate();
});

/**
 * 订单表单 - 事件
 */
watchEffect(() => {
  //selectedKeys.value = [unref(getLocale)];
});

// 1、产品列表 参数：出团日期 + 部门
function getAjaxAutocomplete(formModel, ddlx) {
  let tourDate = formModel.cfsj;
  if (!tourDate || !ddlx) {
    return;
  }
  formModel.travelLine1 = "";
  var params = {tourDate: tourDate, ddlx: ddlx};
  ajaxAutocomplete(params).then( res => {
    options.value = res.result || []
  })
}

function onFilter(v, o) {
  return o!.value.toUpperCase().indexOf(v.toUpperCase()) !== -1
}

function onSelect(value, option, model) {
  let sel = option.filter((item) => item.value === value)
  // console.info("getTravelLine@@@@", value, option, sel);
  // Object.assign(this.schepost, sel[0])
  model.travelLine = value; 
  model.scheduleId = sel[0].id
  model.residue    = sel[0].residue
}

function onChange(value, model) {
  // let sel = option.filter((item) => item.value === value)
  //console.info("getTravelLine@@@@", value, model);
  // Object.assign(this.schepost, sel[0])
  model.travelLine = value.toUpperCase(); 
  // model.scheduleId = sel[0].id
  // model.residue    = sel[0].residue
}

// 表单提交 - 保存
async function handleSubmit() {
  try {
    setModalProps({confirmLoading: true});
    let values = await validate();
    if (values.travelLine1) {
      delete values.travelLine1;
    }
    if (values.travelLine2) {
      delete values.travelLine2;
    }
    //提交表单
    await add(values).then(res => {
      //console.info(res)
      if (res.success) {
        //关闭弹窗
        closeModal();
        $message.createMessage.success("操作成功！")
        //刷新列表
        emit('success', res.message);
      }
    });
  } catch (e) {
  } finally {
    setModalProps({confirmLoading: false});
  }
}

</script>
<style scoped>
:deep(.ant-select-dropdown .ant-select-item) {
  padding: 2px 2px !important;
}

.certain-category-search-dropdown .ant-select-dropdown-menu-item-group-title {
  color: #666;
  font-weight: bold;
}

.certain-category-search-dropdown .ant-select-dropdown-menu-item-group {
  border-bottom: 1px solid #f6f6f6;
}

.certain-category-search-dropdown .ant-select-dropdown-menu-item {
  padding-left: 16px;
  border: 1px red solid;
}

.certain-category-search-dropdown .ant-select-dropdown-menu-item.show-all {
  text-align: center;
  cursor: default;
}

.certain-category-search-dropdown .ant-select-dropdown-menu {
  max-height: 300px;
}

.table {
  width: 100%;
  border: 1px red solid
}
.orderTable{width:100%; background:#fff; text-align:center; margin:0;}
.orderTable thead tr th{border:1px solid #d6dde7; padding:4px 2px; background:#e9eef2; font-size:14px; text-align:center}
.orderTable tbody tr th{border:1px solid #d6dde7; padding:6px 4px; background:#e9eef2; font-weight:normal;}
.orderTable tbody tr td{border:1px solid #d6dde7; padding:4px 2px; }
.orderTable tbody tr th.tdLeft{text-align:left}
.orderTable tbody tr th.tdCenter{text-align:center;}
.orderTable tbody tr td.tdLeft{text-align:left;}
</style>